//
//  OptionButton.m
//  OSClient
//
//  Created by Chaosky on 15/10/19.
//  Copyright © 2015年 1000phone. All rights reserved.
//

#import "OptionButton.h"
// 手动布局头文件
#import <Masonry.h>

@implementation OptionButton
{
    UIButton * button;
    UILabel * label;
}

// 重写初始化方法，扩展初始化方法
- (instancetype)initWithFrame:(CGRect)frame title:(NSString *) title image:(NSString *)imageName
{
    if (self = [super initWithFrame:frame]) {
        button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
        [self addSubview:button];
        
        label = [[UILabel alloc] init];
        label.text = title;
        label.font = [UIFont systemFontOfSize:15];
        label.textAlignment = NSTextAlignmentCenter;
        [self addSubview:label];
        
        // 关闭自动布局
        button.translatesAutoresizingMaskIntoConstraints = NO;
        label.translatesAutoresizingMaskIntoConstraints = NO;
        
        // 创建约束
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            // button距离self左边距为4
            make.left.equalTo(self.mas_left).offset(4);
            // button距离self上边距为2
            make.top.equalTo(self.mas_top).offset(2);
            // 让button的宽度和高度相等
            make.width.equalTo(button.mas_height);
            // button右边距为4
            make.right.equalTo(self.mas_right).offset(-4);
        }];
        
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            // 让label的宽度和button的宽度一样
            make.width.equalTo(button.mas_width);
            // 让label和button间距为4
            make.top.equalTo(button.mas_bottom).offset(4);
            // 让label和button 左对齐和右对齐
            make.left.equalTo(button.mas_left);
            make.right.equalTo(button.mas_right);
            // 让label的底部大于self的底部为4
            make.bottom.greaterThanOrEqualTo(self.mas_bottom).offset(4);
        }];
        button.backgroundColor = [UIColor orangeColor];
    }
    return self;
}

// 让子视图重新布局，系统回调
// 比如：当我们的视图的Rect改变时，系统会通知（通过回调该方法）让视图去改变子视图的Rect
// 我们就可以在这个方法去处理因为父视图改变后，子视图要修改的东西
- (void)layoutSubviews
{
    [self layoutIfNeeded];
    NSLog(@"%@", NSStringFromCGRect(button.bounds));
    button.layer.cornerRadius = button.frame.size.width / 2;
    button.layer.masksToBounds = YES;
}

@end
